#include "server.h"

void *p_r(void *a) //线程运行函数，阻塞等待数据包，根据flags调用相应功能
{
	TEMP temp = *(TEMP *)a;							   //拿取链接产生的文件描述符与数据库句柄
	DATA data;										   //通信用结构体
	char sql[128] = {0};							   //数据库操作字符串
	char *errmsg;									   //数据库错误地址
	char **dbResult;								   //数据库查询结果
	int nRow = 0, nColumn = 0;						   //数据库行与列
	while (recv(temp.fd, &data, sizeof(DATA), 0) != 0) //recv等0表示链接断开
	{
		printf("client:flags=%d,num=%d,name=%s,text1=%s,text2=%s,text3=%s\n",
			   data.flags, data.num, data.name, data.text1, data.text2, data.text3);
		switch (data.flags)
		{
		case 1: //登录

			sqliteget(&temp, &data);
			break;
		case 2: //注册

			sqliteinsert(&temp, &data);
			break;
		case 3: //查询信息

			sqlite_g(&temp, &data);
			break;
		case 4: //查询历史信息

			sqlite_g(&temp, &data);
			break;
		case 5: //修改信息

			sqlite_ch(&temp, &data);
			break;
		case 6: //删除信息
			sqlite_del(&temp, &data);
			break;
		case 7:
			if (sqlite_hes_del(&temp, &data) == -1)
			{
				while(sqlite_init(&temp) != 0)
				{
					printf("历史表格重建失败,系统退出\n");
					kill(getppid(),SIGKILL);
					goto END;
				}
			}
			break;
		}
	}
	printf("用户链接断开\n");
	END:;
}

int main(int argc, const char *argv[]) //阻塞等待链接，创建线程用于通信
{
	int sockfd, acceptfd;
	pthread_t pthread1;
	char sql[128] = {0}; //数据库操作字符串
	char *errmsg;		 //数据库错误信息地址
	struct sockaddr_in hostaddr, clientaddr;
	int addrlen = sizeof(hostaddr);
	TEMP temp;
	sqlite3 *db;

	if (argc < 3)
	{
		fprintf(stderr, "少参数");
	}
	/*网络信息结构体填充*/
	hostaddr.sin_family = AF_INET;
	hostaddr.sin_addr.s_addr = inet_addr(argv[1]); //192.168.50.22
	hostaddr.sin_port = htons(atoi(argv[2]));	   //9999

	if (sqlite3_open("user.db", &db) != SQLITE_OK) //打开数据库
	{
		printf("1错误：%s\n", sqlite3_errmsg(db));
		return -1;
	}
	else
	{
		printf("成功：数据库打开或者创建成功了\n");
	}
	temp.db = db;
	if (sqlite_init(&temp) != 0) //创建表格
	{
		printf("2错误：%s\n", sqlite3_errmsg(db));
		return -1;
	}
	else
	{
		printf("成功：表格打开或者创建成功了\n");
	}

	if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
	{
		ERRLOG("socket error");
	}

	if (bind(sockfd, (struct sockaddr *)&hostaddr, addrlen) == -1)
	{
		ERRLOG("bind error");
	}
	if (listen(sockfd, 5) == -1)
	{
		ERRLOG("listen error");
	}

	while (1)
	{
		if ((acceptfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen)) == -1)
		{
			ERRLOG("accept error");
		}
		temp.fd = acceptfd;
		printf("%d:%s链接\n", ntohs(clientaddr.sin_port), inet_ntoa(clientaddr.sin_addr));

		if (pthread_create(&pthread1, NULL, p_r, &temp) != 0)
		{
			ERRLOG("p_create error");
		}

		pthread_detach(pthread1);
	}
	return 0;
}
